﻿using MS.Cache;
using MS.Entities;
using MS.Enums.Common;
using MS.Utility.Common;
using MS.Utility.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MS.Logic
{
    public partial class MS_Base_UserRoleLogic
    {
        /// <summary>
        /// 批量添加角色用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="uids"></param>
        /// <param name="loginUid"></param>
        public void AddRange(int roleId, List<long> uids, long loginUid)
        {
            List<MS_Base_UserRole> userRoleList = new List<MS_Base_UserRole>();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            foreach (long uid in uids)
            {
                if (!this.IsExists(x => x.RoleId == roleId && x.Uid == uid && x.Status == (int)Status.Normal))
                {
                    userRoleList.Add(new MS_Base_UserRole()
                    {
                        Uid = uid,
                        RoleId = roleId,
                        Status = (int)Status.Normal,
                        CreateTime = DateTimeHelper.GetTime(DateTime.Now),
                        CreateUid = loginUid,
                        UpdateTime = DateTimeHelper.GetTime(DateTime.Now),
                        UpdateUid = loginUid
                    });
                }
            }

            if (userRoleList.Count > 0)
            {
                ms_Base_UserRoleDal.AddRange(userRoleList);
                RemoveCache(userRoleList);
            }
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="roleId"></param>
        private void RemoveCache(List<MS_Base_UserRole> userRoleList)
        {
            //清空LoginUser缓存
            List<string> keys = (from o in userRoleList select CacheConfig.LoginUserKey + o.Uid.ToString()).ToList();
            CacheAdapter.Cache.RemoveAll(keys);
        }
    }
}
